import { resourceLibraryApi, videoApi } from '@/api';
import { pageOpeTypeEnum } from '@/common';
import YmCollaPanes from '@/components/YmCollaPanes';
import { Button, Col, Form, Input, message, Row } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { v4 as uuid } from 'uuid';
import { useYmAliOss, YmAddPageLayout, YmUpload, YmVideoUpload, type YmAddPageLayoutProps } from 'ym-design';

const requireRules = (text: string) => {
  return [{ required: true, message: text }];
};

const { PaneItem } = YmAddPageLayout;

function AddVideoCourseWare() {
  const [searchParam] = useSearchParams();
  const navigator = useNavigate();
  const type = searchParam.get('type');
  const parentId = searchParam.get('parentId');
  const coursewareId = searchParam.get('resourceId');
  const [form] = Form.useForm();
  // { vid: 'v0d560g10001chrg0muqibo96l07hu1g', postUrl: '456' }
  const [loadingDetail, setLoadingDetail] = useState({
    subBtnDis: false,
    viewLoading: false,
  });

  // 使用aliyunoss进行操作
  const customRequest = useYmAliOss();

  useEffect(() => {
    if (type === pageOpeTypeEnum['edit']) {
      resourceLibraryApi.getCourseWareById({ coursewareId }).then((res: any) => {
        const {
          data: { name, picUrl, vedioId },
        } = res;
        form.setFieldsValue({ name, picUrl: [{ uid: uuid(), url: picUrl }], vedioId: { vid: vedioId } });
      });
    }
  }, []);

  const goBackToList = () => {
    navigator('/resourceLibrary/courseWare/videoCourseWare');
  };

  const _formSub = (subType: number) => {
    setLoadingDetail({ subBtnDis: true, viewLoading: true });
    form
      .validateFields()
      .then((values) => {
        const { name, picUrl, vedioId } = values;
        const picUpUrl = picUrl ? picUrl[0].response : vedioId.postUrl;
        const subData: any = {
          name,
          picUrl: picUpUrl,
          vedioId: vedioId.vid,
          parentId,
          coursewareType: 'vido',
        };
        console.log('--addVideoCourseWare--subData--:', subData);
        let requestApi;
        if (type === pageOpeTypeEnum['add']) {
          requestApi = resourceLibraryApi.createCourseWare(subData);
        } else if (type === pageOpeTypeEnum['edit']) {
          subData.coursewareId = coursewareId;
          requestApi = resourceLibraryApi.updateCourseWare(subData);
        } else {
          return message.error('type 未定义');
        }
        requestApi
          .then((res: any) => {
            const { code, msg } = res;
            if (code === '200') {
              message.success(msg || `${type === pageOpeTypeEnum['add'] ? '添加' : '编辑'}成功`);
              if (subType === 1) {
                //保存
                goBackToList();
              } else {
                //保存并继续
                form.resetFields();
              }
            } else {
              message.error(msg);
            }
          })
          .catch((err: any) => {
            console.log('--AddVideoCourseWare--_formSub--err--:', err);
          })
          .finally(() => {
            setLoadingDetail({ subBtnDis: false, viewLoading: false });
          });

        // const requestApi = type === pageOpeTypeEnum['add'] ? resourceLibraryApi.createCourseWare({})
      })
      .catch((err) => {
        setLoadingDetail({ subBtnDis: false, viewLoading: false });
      });
  };
  // 保存
  const sub = () => {
    _formSub(1);
  };

  // 保存并继续添加
  const subAndContinue = () => {
    _formSub(2);
  };

  const operationFooter = useMemo(() => {
    const operationBtn = [
      <Button key="subOnce" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={sub}>
        保存
      </Button>,
      <Button key="subContinue" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={subAndContinue}>
        保存并继续添加
      </Button>,
    ];
    switch (type) {
      case pageOpeTypeEnum['add']:
        return operationBtn;
      case pageOpeTypeEnum['edit']:
        return operationBtn.slice(0, 1); //substring from to
    }
  }, [type, loadingDetail]);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          goBackToList();
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );

  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem
        tabKey="tab1"
        label={(type === pageOpeTypeEnum['add'] ? '添加' : '编辑') + '视频课件'}
        className="pane_tab1"
      >
        <YmCollaPanes collapsible={false} headerTitle="" paneKey={1} collPanesActiveKeys={[1]}>
          <Form layout="horizontal" labelAlign="right" size="middle" form={form}>
            <Row>
              <Col span={24}>
                {/* 接口没存第一帧图片。所以编辑时候，不能确定返回的是否第一帧图片，所以用户删除图片后，不能把旧的封面图再赋值上去。所以编辑必传 */}
                <Form.Item label="封面图" required={type === pageOpeTypeEnum['edit']}>
                  <Form.Item
                    name="picUrl"
                    noStyle
                    rules={type === pageOpeTypeEnum['edit'] ? YmUpload.formRules('请上传课件封面图') : undefined}
                  >
                    <YmUpload
                      maxCount={1}
                      cardWidth={140}
                      cardHeight={140}
                      accept="image/*"
                      customRequest={customRequest}
                    >
                      上传图片
                    </YmUpload>
                  </Form.Item>
                  <p className="safe-edu_upload_warning">图片宽高比例以1.875:1为宜，如：750*400</p>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item name="vedioId" label="视频" rules={requireRules('请上传课件视频')}>
                  <YmVideoUpload
                    getUploadAuthTokenApi={videoApi.getUploadAuthTokenApi}
                    getPlayerAuthTokenApi={async (params) => {
                      const { data } = await videoApi.getPlayerAuthTokenApi(params);
                      return data;
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item name="name" label="名称" rules={requireRules('请输入课件名称')}>
                  <Input placeholder="请输入" maxLength={18} showCount style={{ maxWidth: '300px' }} />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </YmCollaPanes>
      </PaneItem>
    </YmAddPageLayout>
  );
}

export default AddVideoCourseWare;
